
#include <stream.h>
#include <source.h>
#include <panic.h>
#include <stdlib.h>
#include <i2c.h>
#include <ps.h>
#include <led.h>
#include <pio.h>
#include <chain.h>
#include <operator.h>
#include "adi1787.h"
#include "zy_i2c.h"
#include "zy_anc.h"
#include "ui.h"
#include "ui_indicator_leds.h"
#include "kymera_data.h"
#include "battery_monitor.h"
#include "battery_monitor_config.h"
#include "charger_monitor.h"
#include "headset_sm.h"
#include "logging.h"
#include "zy_func_def.h"
#ifdef ENABLE_TOUCH_FOR_IQS7211E
#include "zy_touch_7211e.h"
#endif

#ifndef i2c_addr_1787_8bit
#define i2c_addr_1787_8bit 0x50
#endif
/////////////////////////////////////////////////////// ADI1787 registers ////////////////////////////////////////////////////////////
#ifdef ADI1787_REGISTERS
uint16 ADI1787_ADC_MUTE_REG = 0xC01C;
uint16 ADI1787_DAC_MUTE_REG = 0xC03B;
uint16 ADI1787_FASTDSP_RUN = 0xC061;
uint16 ADI1787_BANK_CONTROL_REG = 0xC062;
uint16 ADI1787_ADC0_VALUE_REG = 0xC01D;
uint16 ADI1787_ADC1_VALUE_REG = 0xC01E;
uint16 ADI1787_ADC2_VALUE_REG = 0xC01F;
uint16 ADI1787_ADC3_VALUE_REG = 0xC020;
uint16 ADI1787_ADC_DAC_POWER = 0xC004;
uint16 ADI1787_MBIAS_PGA_POWER = 0xC005;
uint16 ADI1787_SAI_CLK_PWR = 0xC007;
uint16 ADI1787_POWER_CONTROL = 0xC00D;
uint16 ADI1787_DAC0_ROUTE = 0xC03E;
uint16 ADI1787_DAC1_ROUTE = 0xC03F;
uint16 ADI1787_SPT0_CTRL = 0xC0B6;
uint16 ADI1787_MP_CTRL7 = 0xC091;
uint16 ADI1787_MP_CTRL4 = 0xC08E;
uint16 ADI1787_ASRC_PWR = 0xC009;
uint16 ADI1787_DAC0_VOL = 0xC03C;
uint16 ADI1787_SPT0_CTRL2 = 0xC0B6;

uint8 ADC_MUTE[1] = {0x0F};
uint8 ADC_UNMUTE[1] = {0x00};
uint8 VALUE_00[1] = {0x00};
uint8 VALUE_01[1] = {0x01};
uint8 VALUE_02[1] = {0x02};
uint8 VALUE_03[1] = {0x03};
uint8 VALUE_20[1] = {0x20};
uint8 VALUE_21[1] = {0x21};
uint8 VALUE_10[1] = {0x10};
uint8 VALUE_13[1] = {0x13};
uint8 VALUE_15[1] = {0x15};
uint8 VALUE_17[1] = {0x17};
uint8 VALUE_22[1] = {0x22};
uint8 VALUE_23[1] = {0x23};
uint8 VALUE_33[1] = {0x33};
uint8 VALUE_40[1] = {0x40};
uint8 VALUE_41[1] = {0x41};
uint8 VALUE_60[1] = {0x60};
uint8 ADC02_MUTE[1] = {0x05};
uint8 ADC13_MUTE[1] = {0x0A};
uint8 ADC_POWER_OFF[1] = {0x31};
uint8 ADC_POWER_ON[1] = {0x3F};
uint8 MBIAS_PGA_OFF[1] = {0x03};
uint8 MBIAS_PGA_ON[1] = {0xFF};

uint8 ADC_Value_0[1] = {0x40};
uint8 ADC_Value_6[1] = {0x50};

uint8 BANK_A[1] = {0x40};
uint8 BANK_B[1] = {0x41};
uint8 BANK_C[1] = {0x42};

uint8 DAC_MUTE[1] = {0xF4};
uint8 DAC_UNMUTE[1] = {0x34};
#endif
///////////////////////////////////////////////////    CVC   ///////////////////////////////////////////////////////////////////////
// extern kymera_chain_handle_t cvc_chain_lj;
static uint8 config_cvc(uint8 mode)
{
    // Operator cvc_send_op;
    // cvc_send_op = ChainGetOperatorByRole(cvc_chain_lj, 4);
    // if (cvc_send_op)
    // {
    //     OperatorsStandardSetControl(cvc_send_op, 1, mode);
    //     return 0;
    // }else
    // {
    //     return 1;
    // }
    UNUSED(mode);
    return 0;
}

///////////////////////////////////////////////////    uart   ///////////////////////////////////////////////////////////////////////
bool spp_server_started;
uint8 rxbuf[UART_RECV_BUF_SIZE];
uint8 uartRecvLen_tmp = 0;
uint8 Recv_end = 0;
uint8 para1, para2;
#define AT_A rxbuf[0]
#define AT_T rxbuf[1]
#define AT_PLUS rxbuf[2]
#define AT_INS1 rxbuf[3]
#define AT_INS2 rxbuf[4]
#define AT_INS3 rxbuf[5]
#define AT_INS4 rxbuf[6]
#define AT_INS5 rxbuf[7]
#define AT_INS6 rxbuf[8]
#define AT_INS7 rxbuf[9]
#define AT_INS8 rxbuf[10]
#define AT_INS9 rxbuf[11]
#define AT_INS10 rxbuf[12]
#define AT_INS11 rxbuf[13]
#define AT_INS12 rxbuf[14]
#define AT_INS13 rxbuf[15]
#define AT_INS14 rxbuf[16]
#define AT_INS15 rxbuf[17]
#define AT_INS16 rxbuf[18]
#define AT_INS17 rxbuf[19]
#define AT_INS18 rxbuf[20]
#define AT_INS19 rxbuf[21]
#define AT_INS20 rxbuf[22]

bool zy_gaiaTransport_RfcommSendPacket(gaia_transport *t, uint16 pkt_length, uint8 *packet); //此处声明，定义在gaia_transport_rfcomm.c

bool UartSendData(uint8 *data, uint16 size, uint8 mode);
bool UartSendData(uint8 *data, uint16 size, uint8 mode)
{
    UNUSED(data);
    UNUSED(size);
    UNUSED(mode);
    return TRUE;
}

static uint8 uartRecvData(void)
{
    uint8 buffer_data_len = 0;
    Source src = StreamUartSource();
    uint8 recvLen = SourceSize(src);
    uint8 *recvPtr = (uint8 *)SourceMap(src);
    if (recvLen > 0)
    {
        /* 一次接受收据超过BUFF，直接进入下一步处理 */
        if (recvLen >= UART_RECV_BUF_SIZE)
        {
            memcpy(rxbuf, recvPtr, UART_RECV_BUF_SIZE);
            buffer_data_len = UART_RECV_BUF_SIZE;
            uartRecvLen_tmp = 0;
            Recv_end = 1;
        }
        else
        {
            /* 总计接受收据超过BUFF，舍弃本次接受进入下一步处理 */
            buffer_data_len = uartRecvLen_tmp + recvLen;
            if (buffer_data_len >= UART_RECV_BUF_SIZE)
            {
                buffer_data_len = uartRecvLen_tmp;
                uartRecvLen_tmp = 0;
                Recv_end = 1;
            }
            else
            {
                memcpy(&rxbuf[uartRecvLen_tmp], recvPtr, recvLen);
                uartRecvLen_tmp += recvLen;
                Recv_end = 0;
                /* 收到命令停止符，开始下一步处理 */
                if ((rxbuf[uartRecvLen_tmp - 1] == '\r') || (rxbuf[uartRecvLen_tmp - 1] == '\n'))
                {
                    buffer_data_len = uartRecvLen_tmp;
                    uartRecvLen_tmp = 0;
                    Recv_end = 1;
                }
                else
                {
                    Recv_end = 0;
                }
            }
        }
    }
    SourceDrop(src, recvLen);
    /* 返回接受到的有效数据长度 */
    return buffer_data_len;
}

static uint16 my_i2c_reg_write(int devAddress, int address, int length, uint8 *pData)
{
    // uint8 i;
    // uint16 ret = 0;
    // uint8 tx[length + 2];
    // tx[0] = (uint8)(address >> 8) & 0xff;
    // tx[1] = (uint8)(address)&0xff;
    // for (i = 0; i < length; i++)
    // {
    //     tx[i + 2] = *(pData + i);
    // }
    // ret = I2cTransfer(devAddress, tx, length + 2, 0, 0);
    // if (ret == (length + 3))
    // {
    //   ret = 0;
    // }
    // return ret;
    UNUSED(devAddress);
    i2c_write_byte_for1787(address, pData, length);
    return 0;
}

uint16 my_i2c_reg_read(int devAddress, int address, int length, uint8 *pData)
{
    // uint16 ret = 0;
    // uint8 tx[2];
    // tx[0] = (uint8)(address >> 8) & 0xff;
    // tx[1] = (uint8)(address)&0xff;
    // ret = I2cTransfer(devAddress, tx, 2, pData, length);
    // if (ret == (length+4))
    // {
    //   ret = 0;
    // }
    // return ret;
    UNUSED(devAddress);
    i2c_read_byte_for1787(address, pData, length);
    return 0;
}

static void switchBAVD(uint8 para)
{
    UNUSED(para);
}

static uint16 DSP_ADC(uint8 para1, uint8 para2) // DSP_ADC
{
    uint8 ret;
    uint8 value[1];
    my_i2c_reg_read(i2c_addr_1787_8bit, ADI1787_ADC_MUTE_REG, 1, &ret); // read ADC current statue
    if ((para1 > 0x0f) || (para2 > 0x01))                               //检查参数
    {
        return 1;
    }
    if (para2 == 1) //打开ADC指令
    {
        value[0] = ret & (~para1);
    }
    else //关闭ADC指令
    {
        value[0] = ret | para1;
    }
    return my_i2c_reg_write(i2c_addr_1787_8bit, ADI1787_ADC_MUTE_REG, 1, value); //写入寄存器控制ADC status
}

static uint16 DSP_DAC(uint8 para1, uint8 para2) // DSP_DAC
{
    uint8 ret;
    uint8 value[1];
    my_i2c_reg_read(i2c_addr_1787_8bit, ADI1787_DAC_MUTE_REG, 1, &ret); // read DAC current statue

    if ((para1 > 0x03) || (para2 > 0x01)) //检查参数
    {
        return 1;
    }
    if (para2 == 1) //打开DAC指令
    {
        value[0] = ret & (~(para1 << 6));
    }
    else //关闭ADC指令
    {
        value[0] = ret | (para1 << 6);
    }
    return my_i2c_reg_write(i2c_addr_1787_8bit, ADI1787_DAC_MUTE_REG, 1, value); //写入寄存器控制DAC status
}

static uint16 DSP_PMDY(uint8 para1, uint8 para2) // DSP_增益写入
{
    uint16 addr;
    if (para1 > 4)
    {
        return 1;
    }
    addr = 0xc01d + para1 - 1;
    return my_i2c_reg_write(i2c_addr_1787_8bit, addr, 1, &para2);
}

static uint16 DSP_PLOAD(uint8 para1, uint8 para2) // DSP_增益固化
{
    uint16 _status = 0;
    uint16 adc_value_store_times = 0;
    uint16 requested_words;
    requested_words = PS_SIZE_ADJ(sizeof(uint16));
    if ((para1 > 4) || (para1 <= 0))
    {
        return 1;
    }
    else
    {
        PsRetrieve(adc_value_store_key, &adc_value_store_times, requested_words);
        adc_value_store_times++;
        PsStore(adc_value_store_key, (const uint16 *)&adc_value_store_times, requested_words);
    }

    switch (para1)
    {
    case 1:
        PsStore(adc0_value_key, (const uint16 *)&para2, requested_words);
        break;
    case 2:
        PsStore(adc1_value_key, (const uint16 *)&para2, requested_words);
        break;
    case 3:
        PsStore(adc2_value_key, (const uint16 *)&para2, requested_words);
        break;
    case 4:
        PsStore(adc3_value_key, (const uint16 *)&para2, requested_words);
        break;
    default:
        break;
    }
    return _status;
}

static uint16 DSP_MODEA(void) // DSP_MODEA
{
    return my_i2c_reg_write(i2c_addr_1787_8bit, ADI1787_BANK_CONTROL_REG, 1, BANK_A);
}

static uint16 DSP_MODEB(void) // DSP_MODEB
{
    return my_i2c_reg_write(i2c_addr_1787_8bit, ADI1787_BANK_CONTROL_REG, 1, BANK_B);
}

static uint16 DSP_MODEC(void) // DSP_MODEC
{
    return my_i2c_reg_write(i2c_addr_1787_8bit, ADI1787_BANK_CONTROL_REG, 1, BANK_C);
}

static uint16 DSP_GETR(uint8 para1, uint8 para2, uint8 *pData) // DSP_REBOOT, para1:读取地址，*pData: get value buffer
{
    int addr;
    addr = (para1 * 256) + para2;
    return my_i2c_reg_read(i2c_addr_1787_8bit, addr, 1, pData);
}

static uint16 DSP_BT_POFF(void) //蓝牙关机
{
    MessageSendLater(hs_task1, 0x4002, 0, 3000);
    return 0;
}

static void UART_send_OK(uint8 mode)
{
    rxbuf[0] = 'O';
    rxbuf[1] = 'K';
    rxbuf[2] = '\r';
    rxbuf[3] = '\n';
    UartSendData(rxbuf, 4, mode);
}

static void UART_send_ERROR(uint8 mode)
{
    rxbuf[0] = 'E';
    rxbuf[1] = 'R';
    rxbuf[2] = 'R';
    rxbuf[3] = 'O';
    rxbuf[4] = 'R';
    rxbuf[5] = '\r';
    rxbuf[6] = '\n';
    UartSendData(rxbuf, 7, mode);
}

static void HexToInt(uint8 *s, int l, uint8 *d) // HEX字符串转为int, ex: s "FF" 转为 d 255
{
    UNUSED(l);
    *(d) = ((*s > '9' ? *(s) + 9 : *(s)) << 4) | ((*(s + 1) > '9' ? *(s + 1) + 9 : *(s + 1)) & 0x0F);
}

/*
mode:应答方式，0：uart, 1: spp, 2: gaia
BAVD = <rate>
ADCC = <ADC通道，低4位><打开(1)OR关闭(0)>
DACC = <DAC通道，FF（BIT0）;FB（BIT1）><打开(1)OR关闭(0)>
PMDY = <0x01~0x04,对应 FFL FFR FBL FBR><1个字节的gain值 最大值 0x00 24DB 默认值：0x40 0DB 最小值 0XFF -71.625DB 相当 于mute；>指定通道写GAIN值
PLOAD = 同上，指定通道，将 gain值参数固 话到软件中
MODEA
MODEB
MODEC
MLOOP Loopback测试 指令，测试完 成，需要发送重 启指令（建议放 在测试的最后 一项，使用完这 个指令，需要用 REBOOT指令复 位重启）
REBOOT
RREAD =<寄存器高字节><寄存器低字节>
POFF 关机

*/
void UartCommandHandle(uint8 mode)
{
    if (('A' == AT_A) && ('T' == AT_T) && ('+' == AT_PLUS))
    { //确认是AT指令
        // 1串口通指令
        if (('O' == AT_INS1) && ('K' == AT_INS2) && ('\r' == AT_INS3) && ('\n' == AT_INS4))
        {
            UART_send_OK(mode);
        }
        // 2调波特率指令
        else if (('B' == AT_INS1) && ('A' == AT_INS2) && ('V' == AT_INS3) && ('D' == AT_INS4) && ('=' == AT_INS5) && ('\r' == AT_INS7) && ('\n' == AT_INS8))
        {
            para1 = AT_INS6;
            rxbuf[0] = '+';
            rxbuf[1] = 'B';
            rxbuf[2] = 'A';
            rxbuf[3] = 'V';
            rxbuf[4] = 'D';
            rxbuf[5] = ':';
            rxbuf[6] = para1;
            rxbuf[7] = 'O';
            rxbuf[8] = 'K';
            rxbuf[9] = '\r';
            rxbuf[10] = '\n';
            UartSendData(rxbuf, 11, mode);
            switchBAVD(para1);
        }
        // 3ADC指令,指令示例 打开所有ADC："AT+ADCC=<0x0F><0x01>\r\n"
        else if (('A' == AT_INS1) && ('D' == AT_INS2) && ('C' == AT_INS3) && ('C' == AT_INS4) && ('=' == AT_INS5) && ('\r' == AT_INS18) && ('\n' == AT_INS19))
        {
            HexToInt(rxbuf + 11, 1, &para1);
            HexToInt(rxbuf + 17, 1, &para2);
            if (DSP_ADC(para1, para2))
            {
                UART_send_ERROR(mode);
            }
            else
            {
                UART_send_OK(mode);
            }
        }
        // 4 DAC指令 指令示例 打开所有DAC："AT+DACC=<0x03><0x01>\r\n"
        else if (('D' == AT_INS1) && ('A' == AT_INS2) && ('C' == AT_INS3) && ('C' == AT_INS4) && ('=' == AT_INS5) && ('\r' == AT_INS18) && ('\n' == AT_INS19))
        {
            HexToInt(rxbuf + 11, 1, &para1);
            HexToInt(rxbuf + 17, 1, &para2);
            if (DSP_DAC(para1, para2))
            {
                UART_send_ERROR(mode);
            }
            else
            {
                UART_send_OK(mode);
            }
        }
        // 5 写入GAIN值
        else if (('P' == AT_INS1) && ('M' == AT_INS2) && ('D' == AT_INS3) && ('Y' == AT_INS4) && ('=' == AT_INS5) && ('\r' == AT_INS18) && ('\n' == AT_INS19))
        {
            HexToInt(rxbuf + 11, 1, &para1);
            HexToInt(rxbuf + 17, 1, &para2);
            if (DSP_PMDY(para1, para2))
            {
                UART_send_ERROR(mode);
            }
            else
            {
                UART_send_OK(mode);
            }
        }
        // 6 固化GAIN值
        else if (('P' == AT_INS1) && ('L' == AT_INS2) && ('O' == AT_INS3) && ('A' == AT_INS4) && ('D' == AT_INS5) && ('\r' == AT_INS19) && ('\n' == AT_INS20))
        {
            HexToInt(rxbuf + 12, 1, &para1);
            HexToInt(rxbuf + 18, 1, &para2);
            if (DSP_PLOAD(para1, para2))
            {
                UART_send_ERROR(mode);
            }
            else
            {
                UART_send_OK(mode);
            }
        }
        // 7 MODEA
        else if (('M' == AT_INS1) && ('O' == AT_INS2) && ('D' == AT_INS3) && ('E' == AT_INS4) && ('A' == AT_INS5) && ('\r' == AT_INS6) && ('\n' == AT_INS7))
        {
            if (DSP_MODEA())
            {
                UART_send_ERROR(mode);
            }
            else
            {
                UART_send_OK(mode);
            }
        }
        // 8 MODEB
        else if (('M' == AT_INS1) && ('O' == AT_INS2) && ('D' == AT_INS3) && ('E' == AT_INS4) && ('B' == AT_INS5) && ('\r' == AT_INS6) && ('\n' == AT_INS7))
        {
            if (DSP_MODEB())
            {
                UART_send_ERROR(mode);
            }
            else
            {
                UART_send_OK(mode);
            }
        }
        // 9 MODEC
        else if (('M' == AT_INS1) && ('O' == AT_INS2) && ('D' == AT_INS3) && ('E' == AT_INS4) && ('C' == AT_INS5) && ('\r' == AT_INS6) && ('\n' == AT_INS7))
        {
            if (DSP_MODEC())
            {
                UART_send_ERROR(mode);
            }
            else
            {
                UART_send_OK(mode);
            }
        }
        // 10 LOOPBACK
        else if (('M' == AT_INS1) && ('L' == AT_INS2) && ('O' == AT_INS3) && ('O' == AT_INS4) && ('P' == AT_INS5) && ('\r' == AT_INS6) && ('\n' == AT_INS7))
        {
            UART_send_OK(mode);
            // reset_system();					//重启MCU
        }
        // 11 REBOOT
        else if (('R' == AT_INS1) && ('E' == AT_INS2) && ('B' == AT_INS3) && ('O' == AT_INS4) && ('O' == AT_INS5) && ('T' == AT_INS6) && ('\r' == AT_INS7) && ('\n' == AT_INS8))
        {
            UART_send_OK(mode);
            // reset_system();					//重启MCU
        }
        // 12 READ REGISTER 指令示例 读0x0c1d："AT+RREAD=<0xC01d>\r\n"
        else if (('R' == AT_INS1) && ('R' == AT_INS2) && ('E' == AT_INS3) && ('A' == AT_INS4) && ('D' == AT_INS5) && ('=' == AT_INS6) && ('\r' == AT_INS15) && ('\n' == AT_INS16))
        {
            HexToInt(rxbuf + 12, 1, &para1);
            HexToInt(rxbuf + 14, 1, &para2);
            rxbuf[0] = '+';
            rxbuf[1] = 'R';
            rxbuf[2] = 'R';
            rxbuf[3] = 'E';
            rxbuf[4] = 'A';
            rxbuf[5] = 'D';
            rxbuf[6] = ':';
            // rxbuf[7] = DSP_GETR(para1);
            rxbuf[8] = '\r';
            rxbuf[9] = '\n';
            DSP_GETR(para1, para2, rxbuf + 7);
            UartSendData(rxbuf, 10, mode);
        }
        // 13 BT POWRE OFF
        else if (('P' == AT_INS1) && ('O' == AT_INS2) && ('F' == AT_INS3) && ('F' == AT_INS4) && ('\r' == AT_INS5) && ('\n' == AT_INS6))
        {
            if (DSP_BT_POFF())
            {
                UART_send_ERROR(mode);
            }
            else
            {
                UART_send_OK(mode);
            }
        }
        // 14 reset mcu
        else if (('T' == AT_INS1) && ('S' == AT_INS2) && ('T' == AT_INS3) && ('O' == AT_INS4) && ('P' == AT_INS5) && ('\r' == AT_INS6) && ('\n' == AT_INS7))
        {
            UART_send_OK(mode);
            // reset_system();					//重启MCU
        }
        else if (('D' == AT_INS1) && ('I' == AT_INS2) && ('S' == AT_INS3) && ('R' == AT_INS4) && ('D' == AT_INS5) && ('P' == AT_INS6) && ('\r' == AT_INS7) && ('\n' == AT_INS8))
        {
            UART_send_OK(mode);
            // off_flash_protection();					//解除读保护，擦除所有程序
        }
        /* 佩戴传感器 */
        else if (('L' == AT_INS1) && ('I' == AT_INS2) && ('G' == AT_INS3) && ('H' == AT_INS4) && ('T' == AT_INS5) && ('O' == AT_INS6) && ('N' == AT_INS7) && ('\r' == AT_INS8) && ('\n' == AT_INS9))
        {
            set_light_sensor_enabled(1);
            UART_send_OK(mode);
        }
        else if (('L' == AT_INS1) && ('I' == AT_INS2) && ('G' == AT_INS3) && ('H' == AT_INS4) && ('T' == AT_INS5) && ('O' == AT_INS6) && ('F' == AT_INS7) && ('\r' == AT_INS9) && ('\n' == AT_INS10))
        {
            set_light_sensor_enabled(0);
            UART_send_OK(mode);
        }
        //未知指令
        else
        {
            UART_send_ERROR(mode);
        }
    }
}

void SPPCommandHandleForAiroha(gaia_transport *transport)
{
    uint8 txbuf[20] = {0};
    uint8 value[1];
    uint16 ret0, ret1, ret2, ret3, ret4;
    short gain_ff_l, gain_fb_l, gain_ff_r, gain_fb_r, a, b;
    unsigned char base_adc = 0x40;
    unsigned char value_adc[4];
    unsigned char value_pga[4];
    uint16 adc_value_store_times = 0;
    uint16 requested_words;
    uint16 gain_adc0, gain_adc1, gain_adc2, gain_adc3;
    uint16 gain_pga01, gain_pga11, gain_pga21, gain_pga31;
    requested_words = PS_SIZE_ADJ(sizeof(uint16));
    if ((0x05 == AT_A) && (0x5a == AT_T))
    { /* 确认是洛达测试 */
        /* ANC OFF 指令 */
        if ((0x06 == AT_INS2) && (0x0e == AT_INS3) && (0x00 == AT_INS4) && (0x0b == AT_INS5) && (0x01 == AT_INS6))
        {
            txbuf[0] = 0x05;
            txbuf[1] = 0x5b; /* reply位 */
            txbuf[2] = 0x08; /* len */
            txbuf[3] = 0x00; /* len */
            txbuf[4] = 0x06;
            txbuf[5] = 0x0e;
            txbuf[6] = 0x00;  /* 确认位 */
            txbuf[7] = 0x0b;  /* 0B : ANC OFF操作 */
            txbuf[8] = 0x01;  /* ANC OFF */
            txbuf[9] = 0x00;  /* reserved */
            txbuf[10] = 0x00; /* reserved */
            txbuf[11] = 0x00; /* reserved */
            if (DSP_ADC(0x0f, 0x00))
            {
                txbuf[6] = 0x01; /* 确认位 */
            }
            // UartSendData(txbuf, 12, mode);
            zy_gaiaTransport_RfcommSendPacket(transport, 12, txbuf);
        }
        /* ANC ON 指令 */
        else if ((0x06 == AT_INS2) && (0x0e == AT_INS3) && (0x00 == AT_INS4) && (0x0a == AT_INS5))
        {
            txbuf[0] = 0x05;
            txbuf[1] = 0x5b; /* reply位 */
            txbuf[2] = 0x08; /* len */
            txbuf[3] = 0x00; /* len */
            txbuf[4] = 0x06;
            txbuf[5] = 0x0e;
            txbuf[6] = 0x00;     /* 确认位 */
            txbuf[7] = 0x0a;     /* 0A : ANC ON操作 */
            txbuf[8] = 0x01;     /* 滤波器组数 */
            txbuf[9] = 0x00;     /* ANC MODE */
            txbuf[10] = 0x00;    /* 头戴式 */
            txbuf[11] = 0x00;    /* reserved */
            if (0x01 == AT_INS7) /* FF ON 指令 */
            {
                value[0] = 0x05;
                txbuf[8] = 0x01; /* 滤波器组数 */
                txbuf[9] = 0x01; /* ANC MODE */
                DSP_MODEA();
                if (my_i2c_reg_write(i2c_addr_1787_8bit, ADI1787_ADC_MUTE_REG, 1, value))
                {
                    txbuf[6] = 0x01; /* 确认位 */
                }
            }
            else if ((0x02 == AT_INS7)) /* FB ON 指令 */
            {
                value[0] = 0x0a;
                txbuf[8] = 0x01; /* 滤波器组数 */
                txbuf[9] = 0x02; /* ANC MODE */
                DSP_MODEA();
                if (my_i2c_reg_write(i2c_addr_1787_8bit, ADI1787_ADC_MUTE_REG, 1, value))
                {
                    txbuf[6] = 0x01; /* 确认位 */
                }
            }
            else if ((0x00 == AT_INS7)) /* FF+FB ON 指令 */
            {
                value[0] = 0x00;
                txbuf[8] = 0x01; /* 滤波器组数 */
                txbuf[9] = 0x00; /* ANC MODE */
                DSP_MODEA();
                if (my_i2c_reg_write(i2c_addr_1787_8bit, ADI1787_ADC_MUTE_REG, 1, value))
                {
                    txbuf[6] = 0x01; /* 确认位 */
                }
            }
            else if ((0x04 == AT_INS7)) /* 通透 ON 指令 */
            {
                value[0] = 0x00;
                txbuf[8] = 0x09; /* 滤波器组数 */
                txbuf[9] = 0x04; /* ANC MODE */
                DSP_MODEB();
                if (my_i2c_reg_write(i2c_addr_1787_8bit, ADI1787_ADC_MUTE_REG, 1, value))
                {
                    txbuf[6] = 0x01; /* 确认位 */
                }
            }
            else
            {
                txbuf[6] = 0x01; /* 确认位 */
            }

            // UartSendData(txbuf, 12, mode);
            zy_gaiaTransport_RfcommSendPacket(transport, 12, txbuf);
        }
        /* 写增益指令 */
        else if ((0x06 == AT_INS2) && (0x0e == AT_INS3) && (0x00 == AT_INS4) && (0x0C == AT_INS5))
        {
            txbuf[0] = 0x05;
            txbuf[1] = 0x5b; /* reply位 */
            txbuf[2] = 0x10; /* len */
            txbuf[3] = 0x00; /* len */
            txbuf[4] = 0x06;
            txbuf[5] = 0x0e;
            txbuf[6] = 0x00; /* 确认位 */
            txbuf[7] = 0x0C; /* 0C : 写增益操作 */
            txbuf[8] = AT_INS6;
            txbuf[9] = AT_INS7;
            txbuf[10] = AT_INS8;
            txbuf[11] = AT_INS9;
            txbuf[12] = AT_INS10;
            txbuf[13] = AT_INS11;
            txbuf[14] = AT_INS12;
            txbuf[15] = AT_INS13;
            txbuf[16] = 0x00;
            txbuf[17] = 0x00;
            txbuf[18] = 0x00;
            txbuf[19] = 0x00;
            // gain_ff_l = (AT_INS6 << 8) + AT_INS7;
            // gain_fb_l = (AT_INS8 << 8) + AT_INS9;
            // gain_ff_r = (AT_INS10 << 8) + AT_INS11;
            // gain_fb_r = (AT_INS12 << 8) + AT_INS13;
            gain_ff_l = (AT_INS7 << 8) + AT_INS6; /* 数据小端模式 */
            gain_fb_l = (AT_INS9 << 8) + AT_INS8;
            gain_ff_r = (AT_INS11 << 8) + AT_INS10;
            gain_fb_r = (AT_INS13 << 8) + AT_INS12;
            if (gain_ff_l < -7000)
            {
                gain_ff_l = -7000;
            }
            if (gain_fb_l < -7000)
            {
                gain_fb_l = -7000;
            }
            if (gain_ff_r < -7000)
            {
                gain_ff_r = -7000;
            }
            if (gain_fb_r < -7000)
            {
                gain_fb_r = -7000;
            }
            a = (gain_fb_l * 10) / 375;
            b = (gain_fb_l * 10) % 375;
            if (a < 0) /* 负增益 */
            {
                value_adc[0] = base_adc - a + 1;
                value_pga[0] = (375 + b) / 24;
            }
            else
            {
                value_adc[0] = base_adc - a;
                value_pga[0] = b / 24;
            }
            a = (gain_ff_l * 10) / 375;
            b = (gain_ff_l * 10) % 375;
            if (a < 0) /* 负增益 */
            {
                value_adc[1] = base_adc - a + 1;
                value_pga[1] = (375 + b) / 24;
            }
            else
            {
                value_adc[1] = base_adc - a;
                value_pga[1] = b / 24;
            }
            a = (gain_fb_r * 10) / 375;
            b = (gain_fb_r * 10) % 375;
            if (a < 0) /* 负增益 */
            {
                value_adc[2] = base_adc - a + 1;
                value_pga[2] = (375 + b) / 24;
            }
            else
            {
                value_adc[2] = base_adc - a;
                value_pga[2] = b / 24;
            }
            a = (gain_ff_r * 10) / 375;
            b = (gain_ff_r * 10) % 375;
            if (a < 0) /* 负增益 */
            {
                value_adc[3] = base_adc - a + 1;
                value_pga[3] = (375 + b) / 24;
            }
            else
            {
                value_adc[3] = base_adc - a;
                value_pga[3] = b / 24;
            }
            ret0 = my_i2c_reg_write(i2c_addr_1787_8bit, ADI1787_ADC0_VALUE_REG, 4, value_adc);
            ret1 = my_i2c_reg_write(i2c_addr_1787_8bit, 0xC022, 1, value_pga);
            ret2 = my_i2c_reg_write(i2c_addr_1787_8bit, 0xC024, 1, value_pga + 1);
            ret3 = my_i2c_reg_write(i2c_addr_1787_8bit, 0xC026, 1, value_pga + 2);
            ret4 = my_i2c_reg_write(i2c_addr_1787_8bit, 0xC028, 1, value_pga + 3);
            if (ret0 || ret1 || ret2 || ret3 || ret4)
            {
                txbuf[6] = 0x01; /* 确认位 */
            }
            // UartSendData(txbuf, 20, mode);
            zy_gaiaTransport_RfcommSendPacket(transport, 20, txbuf);
        }
        /* 固话增益指令 */
        else if ((0x06 == AT_INS2) && (0x0e == AT_INS3) && (0x00 == AT_INS4) && (0x0e == AT_INS5))
        {
            txbuf[0] = 0x05;
            txbuf[1] = 0x5b; /* reply位 */
            txbuf[2] = 0x10; /* len */
            txbuf[3] = 0x00; /* len */
            txbuf[4] = 0x06;
            txbuf[5] = 0x0e;
            txbuf[6] = 0x00; /* 确认位 */
            txbuf[7] = 0x0e; /* 0C : 固话增益操作 */
            txbuf[8] = AT_INS6;
            txbuf[9] = AT_INS7;
            txbuf[10] = AT_INS8;
            txbuf[11] = AT_INS9;
            txbuf[12] = AT_INS10;
            txbuf[13] = AT_INS11;
            txbuf[14] = AT_INS12;
            txbuf[15] = AT_INS13;
            txbuf[16] = 0x00;
            txbuf[17] = 0x00;
            txbuf[18] = 0x00;
            txbuf[19] = 0x00;
            // gain_ff_l = (AT_INS6 << 8) + AT_INS7;
            // gain_fb_l = (AT_INS8 << 8) + AT_INS9;
            // gain_ff_r = (AT_INS10 << 8) + AT_INS11;
            // gain_fb_r = (AT_INS12 << 8) + AT_INS13;
            gain_ff_l = (AT_INS7 << 8) + AT_INS6; /* 数据小端模式 */
            gain_fb_l = (AT_INS9 << 8) + AT_INS8;
            gain_ff_r = (AT_INS11 << 8) + AT_INS10;
            gain_fb_r = (AT_INS13 << 8) + AT_INS12;
            if (gain_ff_l < -7000)
            {
                gain_ff_l = -7000;
            }
            if (gain_fb_l < -7000)
            {
                gain_fb_l = -7000;
            }
            if (gain_ff_r < -7000)
            {
                gain_ff_r = -7000;
            }
            if (gain_fb_r < -7000)
            {
                gain_fb_r = -7000;
            }
            a = (gain_fb_l * 10) / 375;
            b = (gain_fb_l * 10) % 375;
            if (a < 0) /* 负增益 */
            {
                value_adc[0] = base_adc - a + 1;
                value_pga[0] = (375 + b) / 24;
            }
            else
            {
                value_adc[0] = base_adc - a;
                value_pga[0] = b / 24;
            }
            a = (gain_ff_l * 10) / 375;
            b = (gain_ff_l * 10) % 375;
            if (a < 0) /* 负增益 */
            {
                value_adc[1] = base_adc - a + 1;
                value_pga[1] = (375 + b) / 24;
            }
            else
            {
                value_adc[1] = base_adc - a;
                value_pga[1] = b / 24;
            }
            a = (gain_fb_r * 10) / 375;
            b = (gain_fb_r * 10) % 375;
            if (a < 0) /* 负增益 */
            {
                value_adc[2] = base_adc - a + 1;
                value_pga[2] = (375 + b) / 24;
            }
            else
            {
                value_adc[2] = base_adc - a;
                value_pga[2] = b / 24;
            }
            a = (gain_ff_r * 10) / 375;
            b = (gain_ff_r * 10) % 375;
            if (a < 0) /* 负增益 */
            {
                value_adc[3] = base_adc - a + 1;
                value_pga[3] = (375 + b) / 24;
            }
            else
            {
                value_adc[3] = base_adc - a;
                value_pga[3] = b / 24;
            }
            gain_adc0 = value_adc[0];
            gain_adc1 = value_adc[1];
            gain_adc2 = value_adc[2];
            gain_adc3 = value_adc[3];
            gain_pga01 = value_pga[0];
            gain_pga11 = value_pga[1];
            gain_pga21 = value_pga[2];
            gain_pga31 = value_pga[3];
            PsRetrieve(adc_value_store_key, &adc_value_store_times, requested_words);
            adc_value_store_times++;
            PsStore(adc_value_store_key, (const uint16 *)&adc_value_store_times, requested_words);
            PsStore(adc0_value_key, (const uint16 *)&gain_adc0, requested_words);
            PsStore(adc1_value_key, (const uint16 *)&gain_adc1, requested_words);
            PsStore(adc2_value_key, (const uint16 *)&gain_adc2, requested_words);
            PsStore(adc3_value_key, (const uint16 *)&gain_adc3, requested_words);
            PsStore(pga01_value_key, (const uint16 *)&gain_pga01, requested_words);
            PsStore(pga11_value_key, (const uint16 *)&gain_pga11, requested_words);
            PsStore(pga21_value_key, (const uint16 *)&gain_pga21, requested_words);
            PsStore(pga31_value_key, (const uint16 *)&gain_pga31, requested_words);
            // UartSendData(txbuf, 20, mode);
            zy_gaiaTransport_RfcommSendPacket(transport, 20, txbuf);
        }
        /* CVC/AEC */
        else if ((0x0d == AT_INS2) && (0x0e == AT_INS3))
        {
            txbuf[0] = 0x05;
            txbuf[1] = 0x5b; /* reply位 */
            txbuf[2] = 0x03; /* len */
            txbuf[3] = 0x00; /* len */
            txbuf[4] = 0x0d;
            txbuf[5] = 0x0e;
            ret0 = 0;
            if (0x00 == AT_INS4) /* CVC bypass */
            {
                ret0 = config_cvc(4);
            }
            else if (0x01 == AT_INS4)
            {
                ret0 = config_cvc(2);
            }
            else
            {
                ret0 = 1;
            }

            if (ret0) /* CVC操作失败 */
            {
                txbuf[6] = 0x04;
            }
            else /* CVC操作成功 */
            {
                txbuf[6] = AT_INS4;
            }
            // UartSendData(txbuf, 7, mode);
            zy_gaiaTransport_RfcommSendPacket(transport, 7, txbuf);
        }
        /* power off */
        else if ((0x09 == AT_INS2) && (0x02 == AT_INS3))
        {
            txbuf[0] = 0x05;
            txbuf[1] = 0x5b; /* reply位 */
            txbuf[2] = 0x04; /* len */
            txbuf[3] = 0x00; /* len */
            txbuf[4] = 0x09;
            txbuf[5] = 0x02;
            // UartSendData(txbuf, 6, mode);
            zy_gaiaTransport_RfcommSendPacket(transport, 6, txbuf);
            MessageSendLater(hs_task1, 0x4002, 0, 3000);
        }
        /* 模式识别 */
        else if ((0x00 == AT_INS2) && (0x0d == AT_INS3))
        {
            txbuf[0] = 0x05;
            txbuf[1] = 0x5b; /* reply位 */
            txbuf[2] = 0x04; /* len */
            txbuf[3] = 0x00; /* len */
            txbuf[4] = 0x00;
            txbuf[5] = 0x0d;
            txbuf[6] = 0x00;
            txbuf[7] = 0x02;
            // UartSendData(txbuf, 8, mode);
            zy_gaiaTransport_RfcommSendPacket(transport, 8, txbuf);
        }
        else
        {

        }
    }
}

void app_uart_handler(Task t, MessageId id, Message payload)
{
    UNUSED(t);
    UNUSED(payload);
    switch (id)
    {
    case MESSAGE_MORE_DATA:
    {
        uartRecvData();
        if (Recv_end != 0)
        {
            UartCommandHandle(SEND_MODE_UART);
            memset(rxbuf, 0, sizeof(rxbuf));
            Recv_end = 0;
        }
    }
    break;
    default:
        break;
    }
}

//////////////////////////////////////////////////////////  ANC /////////////////////////////////////////////////////////////////////
AncTaskData anc_tast;
Task hs_task1;
uint16 anc_state = state_anc_off;
uint16 anc_adaptive_enabled_temp = 0;
uint8 anc_is_changing;
uint8 play_tone_on_anc_changing = 1;
uint8 dac_value_1787;
uint8 anc_led_pin;
bool anc_led_enabled = TRUE;
static void My_ANC_Event_Handler(Task task, MessageId id, Message msg);
static void Set_1787_DAC_Route_FastDsp(void);
static void Set_1787_BankA(void);
static void Set_1787_BankB(void);
static void Set_1787_BankC(void);
static void Set_1787_IIS_Only_Registers(void);
static void Quit_IIS_Only(uint8 *bank);
static void ANC_Normal_ON_Execute(void);
static void ANC_Mild_ON_Execute(void);
static void Monitor_ON_Exeture(void);

uint16 i2c_reg_write(int devAddress, int address, int length, uint8 *pData)
{
    bool ret;
    UNUSED(devAddress);
    ret = i2c_write_byte_for1787(address, pData, length);
    if (!ret)
    {
        DEBUG_LOG_WARN("i2c_reg_write_const error!!!\n");
    }
    return ret;
}

uint16 ADI1787_Registers_write(int devAddress, int address, int length, uint8 *pData)
{
    int m, k, i;
    uint16 ret = 0;
    if (length > 64)
    {
        m = length / 64;
        k = length % 64;
        for (i = 0; i < m; i++)
        {
            ret = i2c_reg_write(devAddress, address + (i << 6), 64, (uint8 *)(pData + (i << 6)));
        }
        if (k > 0)
        {
            ret = i2c_reg_write(devAddress, address + (m << 6), k, (uint8 *)(pData + (m << 6)));
        }
    }
    else
    {
        ret = i2c_reg_write(devAddress, address, length, (uint8 *)pData);
    }
    return ret;
}

static uint16 i2c_reg_write_const(int devAddress, int address, int length, uint8 *pData)
{
    bool ret;
    UNUSED(devAddress);
    ret = i2c_write_byte_for1787(address, pData, length);
    if (!ret)
    {
        DEBUG_LOG_WARN("i2c_reg_write_const error!!!\n");
    }
    return ret;
}

static uint16 ADI1787_registers_write_const(int devAddress, int address, int length, const uint8 *pData)
{
    int m, k, i;
    uint16 ret = 0;
    if (length > 64)
    {
        m = length / 64;
        k = length % 64;
        for (i = 0; i < m; i++)
        {
            ret = i2c_reg_write_const(devAddress, address + (i << 6), 64, (uint8 *)(pData + (i << 6)));
        }
        if (k > 0)
        {
            ret = i2c_reg_write_const(devAddress, address + (m << 6), k, (uint8 *)(pData + (m << 6)));
        }
    }
    else
    {
        ret = i2c_reg_write_const(devAddress, address, length, (uint8 *)pData);
    }
    return ret;
}

void Parst_Adi1787_init_Data(const uint8 *data_ptr, uint16 size)
{
#define end_self_boot 0
#define write_multibyte 1
#define delay_times 2
#define no_operation 3
#define wait_for_pll 4
#define write_single_btye 5
    int current_pos = 0;
    uint16 reg_addr;
    uint16 value_len;
    while (1)
    {
        if (current_pos >= size)
        {
            break;
        }
        switch (*(data_ptr + current_pos))
        {
        case end_self_boot:
            current_pos += size;
            break;
        case write_multibyte:
            value_len = ((*(data_ptr + current_pos + 1)) << 8) + (*(data_ptr + current_pos + 2)) - 2;
            reg_addr = ((*(data_ptr + current_pos + 3)) << 8) + (*(data_ptr + current_pos + 4));
            ADI1787_registers_write_const(i2c_addr_1787_8bit, reg_addr, value_len, (data_ptr + current_pos + 5));
            current_pos += (value_len + 5);
            break;
        case delay_times:
            // HAL_Delay(20);
            current_pos += 3;
            break;
        case no_operation:
            current_pos += 1;
            break;
        case wait_for_pll:
            current_pos += 1;
            break;
        case write_single_btye:
            reg_addr = ((*(data_ptr + current_pos + 1)) << 8) + (*(data_ptr + current_pos + 2));
            ADI1787_registers_write_const(i2c_addr_1787_8bit, reg_addr, 1, (data_ptr + current_pos + 3));
            current_pos += 4;
            break;
        default:
            break;
        }
    }
}

void Init_ADC_Value(void)
{
    uint16 adc_value_store_times = 0;
    uint16 ret_len;
    uint16 store_time = 1;
    uint16 default_adc_value = 0x40;
    uint16 default_pga_ctl2_value = 0x00;
    uint16 adc0_value = 0x40;
    uint16 adc1_value = 0x40;
    uint16 adc2_value = 0x40;
    uint16 adc3_value = 0x40;
    uint16 pga01_value = 0x00;
    uint16 pga11_value = 0x00;
    uint16 pga21_value = 0x00;
    uint16 pga31_value = 0x00;
    uint16 requested_words;
    ret_len = PsRetrieve(adc_value_store_key, NULL, 0);
    requested_words = PS_SIZE_ADJ(sizeof(uint16));
    if (!ret_len)
    {
        adc_value_store_times = 0;
    }
    else
    {
        ret_len = PsRetrieve(adc_value_store_key, &adc_value_store_times, requested_words);
    }
    if (!ret_len || !adc_value_store_times) /* 第一次初始化 */
    {
        PsStore(adc_value_store_key, (const uint16 *)&store_time, requested_words);
        PsStore(adc0_value_key, (const uint16 *)&default_adc_value, requested_words);
        PsStore(adc1_value_key, (const uint16 *)&default_adc_value, requested_words);
        PsStore(adc2_value_key, (const uint16 *)&default_adc_value, requested_words);
        PsStore(adc3_value_key, (const uint16 *)&default_adc_value, requested_words);
        PsStore(pga01_value_key, (const uint16 *)&default_pga_ctl2_value, requested_words);
        PsStore(pga11_value_key, (const uint16 *)&default_pga_ctl2_value, requested_words);
        PsStore(pga21_value_key, (const uint16 *)&default_pga_ctl2_value, requested_words);
        PsStore(pga31_value_key, (const uint16 *)&default_pga_ctl2_value, requested_words);
    }
    else /* 读取配置并初始化ADC VALUE */
    {
        PsRetrieve(adc0_value_key, &adc0_value, requested_words);
        PsRetrieve(adc1_value_key, &adc1_value, requested_words);
        PsRetrieve(adc2_value_key, &adc2_value, requested_words);
        PsRetrieve(adc3_value_key, &adc3_value, requested_words);
        PsRetrieve(pga01_value_key, &pga01_value, requested_words);
        PsRetrieve(pga11_value_key, &pga11_value, requested_words);
        PsRetrieve(pga21_value_key, &pga21_value, requested_words);
        PsRetrieve(pga31_value_key, &pga31_value, requested_words);
        ADI1787_Registers_write(i2c_addr_1787_8bit, 0xc01d, 1, (uint8 *)&adc0_value);
        ADI1787_Registers_write(i2c_addr_1787_8bit, 0xc01e, 1, (uint8 *)&adc1_value);
        ADI1787_Registers_write(i2c_addr_1787_8bit, 0xc01f, 1, (uint8 *)&adc2_value);
        ADI1787_Registers_write(i2c_addr_1787_8bit, 0xc020, 1, (uint8 *)&adc3_value);
        ADI1787_Registers_write(i2c_addr_1787_8bit, 0xc022, 1, (uint8 *)&pga01_value);
        ADI1787_Registers_write(i2c_addr_1787_8bit, 0xc024, 1, (uint8 *)&pga11_value);
        ADI1787_Registers_write(i2c_addr_1787_8bit, 0xc026, 1, (uint8 *)&pga21_value);
        ADI1787_Registers_write(i2c_addr_1787_8bit, 0xc028, 1, (uint8 *)&pga31_value);
    }
}

void save_power_off_ANC_state(void)
{
    uint16 requested_words;
    requested_words = PS_SIZE_ADJ(sizeof(uint16));
    PsStore(anc_state_key, (const uint16 *)&anc_state, requested_words);
}

void disenable_anc_led(void)
{
    anc_led_enabled = FALSE;
    LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 0); /* 闪烁开关 */
    LedConfigure(anc_led_pin, LED_ENABLE, 0);
}

void enable_anc_led(void)
{
    anc_led_enabled = TRUE;
    if (anc_state == state_anc_on)
    {
        LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 0); /* 闪烁开关 */
        LedConfigure(anc_led_pin, LED_ENABLE, 1);
    }
    else if (anc_state == state_monitor_on)
    {
        LedConfigure(anc_led_pin, LED_FLASH_RATE, 0x0a); /* 呼吸灯效 */
        LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 1);  /* 闪烁开关 */
        LedConfigure(anc_led_pin, LED_ENABLE, 1);
    }
}

void Set_Dafault_ANC_State(void) /* 初始化默认设置 */
{
    uint16 ret_len;
    uint16 requested_words;
    ret_len = PsRetrieve(anc_state_key, NULL, 0);
    requested_words = PS_SIZE_ADJ(sizeof(uint16));
    if (!ret_len)
    {
        /* ANC LED 开关配置 */
        anc_led_enabled = TRUE;
        PsStore(anc_led_enabled_key, (const uint16 *)&anc_led_enabled, requested_words);
        /* 第一次上电默认关闭ANC及自适应功能 */
        ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_DAC0_ROUTE, 1, VALUE_22);           // DAC0 route to ASRC 0
        ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_DAC1_ROUTE, 1, VALUE_23);           // DAC1 route to ASRC 1
        ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_ADC_MUTE_REG, 1, ADC_MUTE);         // ADC muted
        ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_ADC_DAC_POWER, 1, ADC_POWER_OFF);   // ADC power off
        ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_MBIAS_PGA_POWER, 1, MBIAS_PGA_OFF); // MBIAS PGA power off
        LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 0);                                         /* 闪烁开关 */
        LedConfigure(anc_led_pin, LED_ENABLE, 0);
        ANC_set_State(state_anc_off);
        PsStore(anc_state_key, (const uint16 *)&anc_state, requested_words);
        /* 自适应ANC相关配置 */
        anc_adaptive_enabled = AncAdaptiveDisenabled;
        anc_on_state = AncOnStateHigh;
        PsStore(anc_adaptive_enabled_key, (const uint16 *)&anc_adaptive_enabled, requested_words);
        PsStore(anc_on_state_key, (const uint16 *)&anc_on_state, requested_words);
    }
    else
    {
        PsRetrieve(anc_state_key, &anc_state, requested_words);
        PsRetrieve(anc_adaptive_enabled_key, &anc_adaptive_enabled, requested_words);
        PsRetrieve(anc_on_state_key, &anc_on_state, requested_words);
        PsRetrieve(anc_led_enabled_key, &anc_led_enabled, requested_words);
        anc_adaptive_enabled_temp = anc_adaptive_enabled;
        ANC_set_State(anc_state);
        if (anc_state == state_anc_off)
        {
            ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_DAC0_ROUTE, 1, VALUE_22);           // DAC0 route to ASRC 0
            ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_DAC1_ROUTE, 1, VALUE_23);           // DAC1 route to ASRC 1
            ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_ADC_MUTE_REG, 1, ADC_MUTE);         // ADC muted
            ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_ADC_DAC_POWER, 1, ADC_POWER_OFF);   // ADC power off
            ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_MBIAS_PGA_POWER, 1, MBIAS_PGA_OFF); // MBIAS PGA power off
            LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 0);                                         /* 闪烁开关 */
            LedConfigure(anc_led_pin, LED_ENABLE, 0);
        }
        else if (anc_state == state_anc_on)
        {
            /* 配置ANC ON状态 */
            if (anc_on_state == AncOnStateHigh)
            {
                MessageSend(AncAdaptiveGetTask(), EventAncAdaptiveSetLevelHigh, 0);
            }
            else if (anc_on_state == AncOnStateMid)
            {
                MessageSend(AncAdaptiveGetTask(), EventAncAdaptiveSetLevelMid, 0);
            }
            else
            {
                MessageSend(AncAdaptiveGetTask(), EventAncAdaptiveSetLevelLow, 0);
            }
            /* 配置是否启用自适应ANC */
            if (anc_adaptive_enabled == AncAdaptiveEnabled)
            {
                MessageSend(AncAdaptiveGetTask(), EventAncAdaptiveStart, 0);
            }
            if (anc_led_enabled)
            {
                LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 0); /* 闪烁开关 */
                LedConfigure(anc_led_pin, LED_ENABLE, 1);
            }
        }
        else if (anc_state == state_monitor_on)
        {
            ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_BANK_CONTROL_REG, 1, BANK_B);
            if (anc_led_enabled)
            {
                LedConfigure(anc_led_pin, LED_FLASH_RATE, 0x0a); /* 呼吸灯效 */
                LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 1);  /* 闪烁开关 */
                LedConfigure(anc_led_pin, LED_ENABLE, 1);
            }
        }
    }
}

void DAC_Fade_Out(void) // EventMyAncDacFadeOut
{
    /* 控制1787DAC淡入淡出 -18.75dB*/
    uint8 val[2];
    MessageCancelAll(AncGetTask(), EventMyAncDacFadeIn);
    if (dac_value_1787 >= 0x40)
    {
        val[0] = dac_value_1787;
        val[1] = dac_value_1787;
        i2c_reg_write(i2c_addr_1787_8bit, ADI1787_DAC0_VOL, 2, val);
        dac_value_1787 -= 2;
        MessageSendLater(AncGetTask(), EventMyAncDacFadeOut, 0, fade_out_delay);
    }
    else
    {
        dac_value_1787 = 0x40;
        anc_is_changing = 0;
    }
}

void DAC_Fade_In(void) // EventMyAncDacFadeIn
{
    /* 控制1787DAC淡入淡出, -18.75dB */
    uint8 val[2];
    MessageCancelAll(AncGetTask(), EventMyAncDacFadeOut);    
    if (dac_value_1787 <= dec_faded_value)
    {
        val[0] = dac_value_1787;
        val[1] = dac_value_1787;
        i2c_reg_write(i2c_addr_1787_8bit, ADI1787_DAC0_VOL, 2, val);
        dac_value_1787 += 2;
        MessageSendLater(AncGetTask(), EventMyAncDacFadeIn, 0, fade_in_delay);
    }
}

static void Set_1787_DAC_Route_FastDsp(void) // EventMySetDacRoute
{
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_DAC0_ROUTE, 1, VALUE_20); // DAC0 route to FAST DSP 0
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_DAC1_ROUTE, 1, VALUE_21); // DAC1 route to FAST DSP 1
}

static void Set_1787_BankA(void) // EventMyAncSetBankA
{
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_BANK_CONTROL_REG, 1, BANK_A); // BANK A
    if (anc_state == state_anc_off)
    {
        Set_1787_DAC_Route_FastDsp();
    }
    dac_value_1787 = dec_faded_value;
    DAC_Fade_Out();
    if (anc_led_enabled)
    {
        LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 0); /* 闪烁开关 */
        LedConfigure(anc_led_pin, LED_ENABLE, 1);
    }
    ANC_set_State(state_anc_on);
}

static void Set_1787_BankB(void) // EventMyAncSetBankB
{
    if (restore_gain_in_bank_B)
    {
        uint8 val[4] = {0x40, 0x40, 0x40, 0x40};
        i2c_reg_write(i2c_addr_1787_8bit, 0xc01d, 4, val);
        i2c_reg_write(i2c_addr_1787_8bit, 0xc022, 1, VALUE_00);
        i2c_reg_write(i2c_addr_1787_8bit, 0xc024, 1, VALUE_00);
        i2c_reg_write(i2c_addr_1787_8bit, 0xc026, 1, VALUE_00);
        i2c_reg_write(i2c_addr_1787_8bit, 0xc028, 1, VALUE_00);
    }
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_BANK_CONTROL_REG, 1, BANK_B);
    if (anc_state == state_anc_off)
    {
        Set_1787_DAC_Route_FastDsp();
    }
    dac_value_1787 = dec_faded_value;
    DAC_Fade_Out();
    if (anc_led_enabled)
    {
        LedConfigure(anc_led_pin, LED_FLASH_RATE, 0x0a); /* 呼吸灯效 */
        LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 1);  /* 闪烁开关 */
        LedConfigure(anc_led_pin, LED_ENABLE, 1);
    }
    ANC_set_State(state_monitor_on);
}

static void Set_1787_BankC(void) // EventMyAncSetBankC
{
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_BANK_CONTROL_REG, 1, BANK_C); // BANK C
    if (anc_state == state_anc_off)
    {
        Set_1787_DAC_Route_FastDsp();
    }
    dac_value_1787 = dec_faded_value;
    DAC_Fade_Out();
    if (anc_led_enabled)
    {
        LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 0); /* 闪烁开关 */
        LedConfigure(anc_led_pin, LED_ENABLE, 1);
    }
    ANC_set_State(state_anc_on);
}

static void Set_1787_Not_Change_Bank(void) // EventMyAncSetNotChangeBank
{
    if (anc_state == state_anc_off)
    {
        Set_1787_DAC_Route_FastDsp();
    }
    if (anc_on_state == AncOnStateHigh)
    {
        Anc_Adaptive_Set_Level_High();
    }
    else if (anc_on_state == AncOnStateMid)
    {
        Anc_Adaptive_Set_Level_Mid();
    }
    else
    {
        Anc_Adaptive_Set_Level_Low();
    }
    dac_value_1787 = dec_faded_value;
    DAC_Fade_Out();
    if (anc_led_enabled)
    {
        LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 0); /* 闪烁开关 */
        LedConfigure(anc_led_pin, LED_ENABLE, 1);
    }
    ANC_set_State(state_anc_on);
}

static void Set_1787_IIS_Only_Registers(void) // EventMyAncSetIisOnlyRegitser
{
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_DAC0_ROUTE, 1, VALUE_22);           // DAC0 route to ASRC 0
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_DAC1_ROUTE, 1, VALUE_23);           // DAC1 route to ASRC 1
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_ADC_MUTE_REG, 1, ADC_MUTE);         // ADC muted
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_ADC_DAC_POWER, 1, ADC_POWER_OFF);   // ADC power off
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_MBIAS_PGA_POWER, 1, MBIAS_PGA_OFF); // MBIAS PGA power off
    dac_value_1787 = dec_faded_value;
    DAC_Fade_Out();
    if (anc_led_enabled)
    {
        LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 0); /* 闪烁开关 */
        LedConfigure(anc_led_pin, LED_ENABLE, 0);
    }
    ANC_set_State(state_anc_off);
}

void Enter_IIS_Only(void) // EventMyEnterIisOnly
{
    dac_value_1787 = 0x40;
    DAC_Fade_In();
    MessageSendLater(AncGetTask(), EventMyAncSetIisOnlyRegitser, 0, fade_between_delay);
    if (anc_led_enabled)
    {
        LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 0); /* 闪烁开关 */
        LedConfigure(anc_led_pin, LED_ENABLE, 0);
    }
}

static void Quit_IIS_Only(uint8 *bank)
{
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_ADC_DAC_POWER, 1, ADC_POWER_ON);   // ADC power on
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_MBIAS_PGA_POWER, 1, MBIAS_PGA_ON); // MBIAS PGA power on
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_ADC_MUTE_REG, 1, ADC_UNMUTE);      // ADC Unmuted
    ADI1787_Registers_write(i2c_addr_1787_8bit, ADI1787_BANK_CONTROL_REG, 1, bank);
    if (restore_gain_in_bank_B)
    {
        Init_ADC_Value();
    }
}

void ANC_OFF(void) // EventMyAncOff
{
    anc_adaptive_enabled_temp = anc_adaptive_enabled_temp | anc_adaptive_enabled;
    if (anc_adaptive_enabled)
    {
        MessageSend(AncAdaptiveGetTask(), EventAncAdaptiveStop, 0);
    }
    if (play_tone_on_anc_changing)
    {
        Ui_InjectUiInput(ui_input_my_anc_off);
    }
    MessageSendLater(AncGetTask(), EventMyEnterIisOnly, 0, anc_prompt_time_anc_off);
}

static void ANC_Normal_ON_Execute(void) // EventMyAncOnExeture
{
    dac_value_1787 = 0x40;
    DAC_Fade_In();
    MessageSendLater(AncGetTask(), EventMyAncSetNotChangeBank, 0, fade_between_delay);
    if (anc_led_enabled)
    {
        LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 0); /* 闪烁开关 */
        LedConfigure(anc_led_pin, LED_ENABLE, 1);
    }
}

void ANC_Normal_ON(void) //正常降噪模式 EventMyAncOn
{
    uint8 response[3] = {0x0b, 0x0b, 0x00};
    if (anc_state == state_anc_off)
    {
        Quit_IIS_Only(BANK_A);
    }
    else
    {
        /* 通透模式会重置产线ADC gain，在这里恢复 */
        Init_ADC_Value();
    }
    if (play_tone_on_anc_changing)
    {
        Ui_InjectUiInput(ui_input_my_anc_on);
        // MessageSendLater(KymeraGetTask(), MESSAGE_STREAM_DISCONNECT, NULL, 10000);
    }
    MessageSendLater(AncGetTask(), EventMyAncOnExeture, 0, anc_prompt_time_anc_on);

    response[2] = (uint8)(anc_on_state | (anc_adaptive_enabled_temp << 4) | (ANC_ADAPTIVE_SUPPORTED << 7));
    GaiaSendPacket(gaia_get_transport(), GAIA_VENDOR_QTIL, GAIA_EVENT_NOTIFICATION, GAIA_STATUS_NONE, 3, response);

    if (anc_adaptive_enabled_temp)
    {
        anc_adaptive_enabled_temp = FALSE;
        MessageSendLater(AncAdaptiveGetTask(), EventAncAdaptiveStart, 0, 5000);
    }
}

static void ANC_Mild_ON_Execute(void) // EventMyAncMildOnExeture
{
    dac_value_1787 = 0x40;
    DAC_Fade_In();
    MessageSendLater(AncGetTask(), EventMyAncSetBankC, 0, fade_between_delay);
}

void ANC_Mild_ON(void) //轻度降噪模式 BANK_C
{
    if (anc_state == state_anc_off)
    {
        Quit_IIS_Only(BANK_C);
    }
    else
    {
        /* 通透模式会重置产线ADC gain，在这里恢复 */
        Init_ADC_Value();
    }
    if (play_tone_on_anc_changing)
    {
        Ui_InjectUiInput(ui_input_my_anc_on);
        // MessageSendLater(KymeraGetTask(), MESSAGE_STREAM_DISCONNECT, NULL, 1800);
    }
    MessageSendLater(AncGetTask(), EventMyAncMildOnExeture, 0, anc_prompt_time_anc_on);
}

static void Monitor_ON_Exeture(void) // EventMyMonitorOnExeture
{
    dac_value_1787 = 0x40;
    DAC_Fade_In();
    MessageSendLater(AncGetTask(), EventMyAncSetBankB, 0, fade_between_delay);
}

void Monitor_ON(void) // 环境音 EventMyMonitorOn
{
    anc_adaptive_enabled_temp = anc_adaptive_enabled_temp | anc_adaptive_enabled;
    if (anc_adaptive_enabled)
    {
        MessageSend(AncAdaptiveGetTask(), EventAncAdaptiveStop, 0);
    }
    if (anc_state == state_anc_off)
    {
        Quit_IIS_Only(BANK_B);
    }
    if (play_tone_on_anc_changing)
    {
        Ui_InjectUiInput(ui_input_my_anc_ambient);
        // MessageSendLater(KymeraGetTask(), MESSAGE_STREAM_DISCONNECT, NULL, 1800);
    }
    MessageSendLater(AncGetTask(), EventMyMonitorOnExeture, 0, anc_prompt_time_anc_on);
}

void ANC_set_State(uint16 state)
{
    anc_state = state;
    if (anc_state != state_anc_off)
    {
        MessageCancelAll(AncGetTask(), EventMySetPllSyncASRC);
        MessageSendLater(AncGetTask(), EventMySetPllSyncInternal, 0, 0);
    }else
    {
        MessageCancelAll(AncGetTask(), EventMySetPllSyncInternal);
        MessageSendLater(AncGetTask(), EventMySetPllSyncASRC, 0, 0);
    }
}

static void ANC_Function_Mode_On(void)
{
    LedConfigure(anc_led_pin, LED_DUTY_CYCLE, 0x3ff);      /* 亮度控制 */
    LedConfigure(anc_led_pin, LED_FLASH_MIN_HOLD, 0x7a12); /* 闪烁控制 0.5 s/16µs*/
    LedConfigure(anc_led_pin, LED_FLASH_MAX_HOLD, 0x7a12); /* 闪烁控制 */
    LedConfigure(anc_led_pin, LED_FLASH_RATE, 0x04);       /* 呼吸灯效 */
    LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 1);        /* 闪烁开关 */
    LedConfigure(anc_led_pin, LED_ENABLE, 1);              /* 开关 */
}

void ANC_task_init(Task init_task)
{
    /* 初始化任务 */
    hs_task1 = init_task;
    memset(&anc_tast, 0, sizeof(anc_tast));
    anc_tast.task.handler = My_ANC_Event_Handler;
}

void ANC_led_init(uint8 led_num)
{
    // uint32 mask;
    // uint16 pio, bank;
    // pio = (uint16)(65 + led_num);
    // bank = (uint16)(pio / 32);
    // mask = 1 << led_num;
    // PioSetMapPins32Bank(bank, mask, 0);
    // PioSetFunction(pio, LED);
    anc_led_pin = led_num;
    LedConfigure(anc_led_pin, LED_DUTY_CYCLE, 0x3ff);      /* 亮度控制 */
    LedConfigure(anc_led_pin, LED_FLASH_MIN_HOLD, 0x7a12); /* 闪烁控制 0.5 s/16µs*/
    LedConfigure(anc_led_pin, LED_FLASH_MAX_HOLD, 0x7a12); /* 闪烁控制 */
    LedConfigure(anc_led_pin, LED_FLASH_RATE, 0x0a);       /* 呼吸灯效 */
    LedConfigure(anc_led_pin, LED_FLASH_ENABLE, 0);        /* 闪烁开关 */
    LedConfigure(anc_led_pin, LED_ENABLE, 0);              /* 开关 */
}

uint16 battery_detect_times = 0;
bool led_is_battery_low_indication = FALSE;
void my_battery_low_prompt_indcation_start(void){
    battery_detect_times = 0;
    MessageSendLater(AncGetTask(), EventMyBatteryLowPrompt, 0, 10000);
}

void my_battery_low_prompt_indcation_stop(void){
    MessageCancelAll(AncGetTask(), EventMyBatteryLowPrompt);
}

static void Battery_Low_Prompt_Handler(void){
    if ((!BatteryMonitor_IsGood()) && (!Charger_IsCharging()))
    {
        if (appBatteryGetVoltageAverage() < appConfigBatteryVoltageCritical())
        {
            Ui_InjectUiInput(ui_input_sm_power_off);
        }
        else if ((battery_detect_times % 60) == 0) //30分钟进行一次低电提醒提示
        {
            Ui_InjectUiInput(ui_input_my_battery_low);
            MessageSendLater(KymeraGetTask(), MESSAGE_STREAM_DISCONNECT, NULL, 1800);
            battery_detect_times = 1;
            led_is_battery_low_indication = TRUE;
        }else
        {
            battery_detect_times++;
        }
    }else
    {
        battery_detect_times = 0;
        if (led_is_battery_low_indication)
        {
            led_is_battery_low_indication = FALSE;
            MessageSendLater(UiLeds_GetUiLedsTask(), ui_input_my_battery_ok, NULL, 0);
        }
    }
    MessageCancelAll(AncGetTask(), EventMyBatteryLowPrompt);
    MessageSendLater(AncGetTask(), EventMyBatteryLowPrompt, 0, 30000); //30s进行一次电池检测
}

static void My_ANC_Event_Handler(Task task, MessageId id, Message msg)
{
    UNUSED(task);
    UNUSED(msg);
    uint8 value;
    switch (id)
    {
    case EventMyAncOff:
        ANC_OFF();
        break;
    case EventMyAncOn:
        ANC_Normal_ON();
        break;
    case EventMyMonitorOn:
        Monitor_ON();
        break;
    case EventMyAncMildOn:
        ANC_Mild_ON();
        break;
    case EventMySetDacRoute:
        Set_1787_DAC_Route_FastDsp();
        break;
    case EventMyAncSetBankA:
        Set_1787_BankA();
        break;
    case EventMyAncSetBankB:
        Set_1787_BankB();
        break;
    case EventMyAncSetBankC:
        Set_1787_BankC();
        break;
    case EventMyAncSetNotChangeBank:
        Set_1787_Not_Change_Bank();
        break;
    case EventMyAncSetIisOnlyRegitser:
        Set_1787_IIS_Only_Registers();
        break;
    case EventMyAncDacFadeOut:
        DAC_Fade_Out();
        break;
    case EventMyAncDacFadeIn:
        DAC_Fade_In();
        break;
    case EventMyEnterIisOnly:
        Enter_IIS_Only();
        break;
    case EventMyAncOnExeture:
        ANC_Normal_ON_Execute();
        break;
    case EventMyMonitorOnExeture:
        Monitor_ON_Exeture();
        break;
    case EventMyAncMildOnExeture:
        ANC_Mild_ON_Execute();
        break;
    case EventMyAdiPdSetDown:
        PioSetDir32Bank(0, ADI1787_PD_PIN, ADI1787_PD_PIN); //设置GPIO输出模式
        PioSet32Bank(0, ADI1787_PD_PIN, 0);                 //拉低GPIO
        LedConfigure(anc_led_pin, LED_ENABLE, 0);           /* LED开关 */
        Extern_DCDC_DeInit();
        MessageSendLater(UiLeds_GetUiLedsTask(), ui_input_my_wired_audio_disconnected, NULL, 100);
        MessageSendLater(UiLeds_GetUiLedsTask(), ui_input_my_led_stop_low_pir, NULL, 100);
        break;
    case EventMyAdiSpt0SetUp:
        i2c_reg_write(i2c_addr_1787_8bit, 0xC00A, 1, VALUE_03); /* SPT0 */
        break;
    case EventMyAdiSpt0SetDown:
        i2c_reg_write(i2c_addr_1787_8bit, 0xC00A, 1, VALUE_00); /* SPT0 */
        break;
    case EventMyRestoreVolume:
        restore_volume();
        break;
    case EventMyAncFuncMode:
        ANC_Function_Mode_On();
        break;
    case EventMyBatteryLowPrompt:
        Battery_Low_Prompt_Handler();
        break;
    case EventMySetPllSyncInternal:
        value = 0xc8;
        i2c_reg_write(i2c_addr_1787_8bit, 0xc00e, 1, &value);
        break;
    case EventMySetPllSyncASRC:
        value = 0x88;
        i2c_reg_write(i2c_addr_1787_8bit, 0xc00e, 1, &value);
        break;
    case EventMyVoiceDial_Stop:
        voice_dail_is_opened = FALSE;
        break;
#ifdef ENABLE_TOUCH_FOR_IQS7211E
    case EventMyIQS7211EPalmGestureStop:
        IQS7211E_Palm_Gesture_Stop();
        break;
#endif
    default:
        break;
    }
}
